﻿/*
类名：查询模块类
说明：弹出框模板html、id querycontain
引用类库：'leaflet'
"plugins/scrollbar":滚动条插件
"icheck":checkbox样式插件
"analysis/addcad":叠加CAD与SHP类
*/

define("query/contain", ['leaflet', "plugins/icheck", "leaflet/draw", "plugins/scrollbar", "analysis/addcad"], function (L) {
    L.DCI.Contain = L.Class.extend({

        /*类ID*/
        id: 'querycontain',

        /*选取服务地址*/
        url: '',

        /*地图*/
        _map: '',

        /*绘制工具*/
        tools: {
            point: null,
            polyline: null,
            polygon: null
        },

        /*传出查询参数*/
        data: {
            query_style: null,        //选取方式
            query_geo: null,           //选取区域
            query_content: null,     //查询范围
            query_attribute: [],    //查询属性
        },
        currentHandler_id: null,//当前选择的方式
        /*初始化*/
        initialize: function (_returndata) {
            this._map = L.DCI.App.pool.get("map");
            if ($('.query-choose-contain').length == 0 && _returndata) {
                var _this = this;
                this._returndata = _returndata;
                this.data = {
                    query_style: null,        //选取方式
                    query_geo: null,           //选取区域
                    query_content: null,     //查询范围
                    query_attribute: [],    //查询属性
                };
                $.get('modules/query/query.contain.xml', function (d) {         //读取配置文件
                    var nodes = $(d).children().children();
                    var html = [];
                    html.push('<div id="query-choose-contain-id" class="query-choose-contain" style="opacity:0;">');
                    html.push('<div id="query-choose-header-contain-id"  class="query-choose-header-contain">');
                    html.push('<span>分区查询</span>');
                    html.push('<span class="icon-close2 query-choose-contain-close "></span>');
                    html.push('</div>');
                    nodes.each(function () {
                        if (this.nodeName == "choose") {
                            if (this.attributes["visible"]["value"] == "true") {
                                _this._chooseNode = true;
                                html.push('<div class="choose-style-choose">');
                                html.push('<span class="choose-style-choose-name">' + this.attributes["name"]["value"] + '</span>');
                                $(this).children().each(function (i) {
                                    if (i == 0) {
                                        html.push('<a id="' + this.attributes['name']["value"] + '_' + i + '" style="margin-left:5px;"><span class="' + this.attributes['class']["value"] + '"></span><span style="margin-left: 5px;margin-right: 25px;">' + this.attributes['name']["value"] + '</span></a>');
                                    }
                                    else {
                                        html.push('<a  id="' + this.attributes['name']["value"] + '_' + i + '" ><span class="' + this.attributes['class']["value"] + '"></span><span style="margin-left: 5px;margin-right: 25px;">' + this.attributes['name']["value"] + '</span></a>');
                                    }
                                });
                                html.push('</div>');
                            }
                        } else if (this.nodeName == "choosecs") {
                            if (this.attributes["visible"]["value"] == "true") {
                                _this._choosecsNode = true;
                                html.push('<div class="choose-style-choose-cs">');
                                html.push('<span class="choose-style-choose-cs-name">' + this.attributes["name"]["value"] + '</span>');
                                $(this).children().each(function (i) {
                                    if (i == 0) {
                                        html.push('<a  id="' + this.attributes['name']["value"] + '_' + i + '"  style="margin-left:5px;"><span class="' + this.attributes['class']["value"] + '"></span><span style="margin-left: 5px;margin-right: 9px;">' + this.attributes['name']["value"] + '</span></a>');
                                    }
                                    else {
                                        html.push('<a id="' + this.attributes['name']["value"] + '_' + i + '" ><span class="' + this.attributes['class']["value"] + '"></span><span style="margin-left: 5px;margin-right: 11px;">' + this.attributes['name']["value"] + '</span></a>');
                                    }
                                });
                                html.push('</div>');
                            }
                        } else if (this.nodeName == "thirdchoose") {
                            _this.thirdSelect = { id: "", items: [], features: [] };
                            //判断该节点是否可见
                            if (this.attributes["visible"]["value"] == "true") {
                                //构建标签节点
                                html.push('<div class="choose-test-choose" id="' + this.nodeName + '" style="height:auto;">');
                                html.push('<span>' + this.attributes["name"]["value"] + '</span>');
                                var id = this.attributes["id"].value;
                                html.push('<select id="' + id + '"></select>');
                                _this.thirdSelect.id = id;
                                var htmlItem = "";
                                $(this).children().each(L.bind(function (i, evt) {
                                    var visible = evt.attributes["visible"]["value"];
                                    if (visible == "true") {
                                        var itemId = evt.attributes["id"]["value"];
                                        var itemName = evt.attributes["name"]["value"];
                                        var url = evt.attributes["url"]["value"];
                                        var readFiled = evt.attributes["readFiled"]["value"];
                                        _this.thirdSelect.items.push({ id: itemId, features: {}, url: url, readFiled: readFiled });
                                        htmlItem += '<div class="choose-test-radio"><input type="radio" name="' + id + '" value="' + itemId + '"><span>' + itemName + '</span>' +
                                            '<select id="' + itemId + '"></select></div>';
                                    }
                                }, this));
                                if (htmlItem != "") html.push('<div class="choose-test-radio_container">' + htmlItem + '</div>');
                                html.push('</div>');

                                _this.thirdchooseNode = true;

                                //查找父节点的要素
                                _this.query = L.esri.Tasks.query(this.attributes['url']["value"]);
                                if (this.attributes["readFiled"]) {
                                    _this.query.fields([this.attributes["readFiled"]["value"]]);
                                }
                                _this.query.run(L.bind(function (error, featureCollection, response) {
                                    $("#" + _this.thirdSelect.id).bind('click', function (e) {
                                        $("input[name=" + _this.thirdSelect.id + "]").attr('checked', false);
                                        _this._changeHandler(_this.thirdSelect.id, _this.currentHandler_id);//选择的范围类型变换
                                        var selectFeature = _this.thirdSelect.features[$("#" + _this.thirdSelect.id).val()];
                                        if (selectFeature) {
                                            _this.data.query_geo = L.dci.app.util.convertEsriToLeaflet(_this._map, selectFeature, "Polygon");
                                            _this._hightLight(selectFeature.geometry);
                                        }
                                    });
                                    //父节点select改变时触发 
                                    $("#" + _this.thirdSelect.id).unbind("change");
                                    $("#" + _this.thirdSelect.id).change(L.bind(function (e) {
                                        _this._changeHandler(_this.thirdSelect.id, _this.currentHandler_id);//选择的范围类型变换
                                        //获取选中的值
                                        var selectedVal = $("#" + _this.thirdSelect.id).val();
                                        var selectFeature = _this.thirdSelect.features[selectedVal];
                                        if (selectFeature) {
                                            _this.data.query_geo = L.dci.app.util.convertEsriToLeaflet(_this._map, selectFeature, "Polygon");
                                            _this._hightLight(selectFeature.geometry);
                                        }

                                        if (selectFeature && selectFeature.geometry) {
                                            var geometry = {};//将esri类型的geometry转换为leaflet的类型
                                            geometry.coordinates = selectFeature.geometry.rings;
                                            geometry.type = "Polygon";

                                            //循环填充子节点的下拉框
                                            for (var k = 0 ; k < _this.thirdSelect.items.length; k++) {
                                                var child = _this.thirdSelect.items[k];
                                                $("#" + child.id).empty();//清空下拉框
                                                //$("input[name=" + _this.thirdSelect.id + "]").attr('checked', false);

                                                $("input[name=" + _this.thirdSelect.id + "]").unbind("change");
                                                $("input[name=" + _this.thirdSelect.id + "]").change(function () {//单选框变换时高亮显示对应的select和图形
                                                    var target = arguments[0].target;
                                                    if (target.checked) {
                                                        _this._changeHandler($(target).val(), _this.currentHandler_id);//选择的范围类型变换
                                                        var val = $("#" + $(target).val()).val();
                                                        for (var f in _this.thirdSelect.items) {
                                                            var item = _this.thirdSelect.items[f];
                                                            if ($(target).val() == item.id) {
                                                                var feature = item.features[val];
                                                                if (feature) {
                                                                    _this.data.query_geo = L.dci.app.util.convertEsriToLeaflet(_this._map, feature, "Polygon");
                                                                    _this._hightLight(feature.geometry);
                                                                }
                                                                break;
                                                            }
                                                        }
                                                    }
                                                });
                                                //绑定选择变化时触发
                                                $("#" + child.id).unbind("change");
                                                $("#" + child.id).change(L.bind(function (e) {
                                                    var target = e.currentTarget;
                                                    for (var f in _this.thirdSelect.items) {
                                                        var item = _this.thirdSelect.items[f];
                                                        if (target.id == item.id) {
                                                            _this._changeHandler(target.id, _this.currentHandler_id);//选择的范围类型变换
                                                            var val = $(target).val();
                                                            var feature = item.features[val];
                                                            if (feature) {
                                                                _this.data.query_geo = L.dci.app.util.convertEsriToLeaflet(_this._map, feature, "Polygon");
                                                                _this._hightLight(feature.geometry);
                                                            }
                                                            break;
                                                        }
                                                    }
                                                }, this));

                                                child.me = this;
                                                var queryItem = L.esri.Tasks.query(child.url, { proxy: true });//根据父节点的范围查询图层与之相交的要素
                                                queryItem.intersects(geometry);
                                                queryItem.run(L.bind(function (faild, f, r) {
                                                    if (r) {
                                                        for (var j in r.features) {
                                                            var feature = r.features[j];
                                                            var value = feature.attributes[this.readFiled];
                                                            var value_id = value + "_" + j;
                                                            $("#" + this.id).append('<option value ="' + value_id + '">' + value + '</option>');
                                                            this.features[value_id] = feature;//将要素加入到数组
                                                        }
                                                    }
                                                }, child));
                                                $("#" + child.id).append('<div class="choose-test-choose" style=" border: solid 1px #d2d2d2;"></div>');
                                            }
                                        }
                                    }, this));
                                    _this.thirdSelect.features = {};
                                    //填充父节点的选项
                                    if (response && response.features) {
                                        for (var i in response.features) {
                                            var feature = response.features[i];
                                            var value = feature.attributes[this.attributes["readFiled"]["value"]];
                                            var value_id = value + "_" + i;
                                            $("#" + _this.thirdSelect.id).append('<option value ="' + value_id + '">' + value + '</option>');
                                            _this.thirdSelect.features[value_id] = feature;//将要素加入到数组
                                        }
                                    }
                                    //$("#" + _this.thirdSelect.id).change();

                                }, this));
                            }
                        } else if (this.nodeName == "attribute") {
                            if (this.attributes["visible"]["value"] == "true") {
                                _this.attributeNode = true;
                                html.push('<span class="choose-attribute-choose-name">' + this.attributes["name"]["value"] + '</span>');
                                html.push('<div class="choose-attribute-choose">');
                                $(this).children().each(function (i) {
                                    html.push('<div class="choose-attribute-checkbox"><input type="checkbox"><span>' + this.attributes["name"]["value"] + '</span></div>');
                                });
                                html.push('</div>');
                            }
                        }
                    });
                    html.push('<div class="clear"></div>');
                    html.push('<div><button>确定</button></div>');
                    html.push('</div>');

                    $(".out-container").append(html.join(' '));
                    $(".choose-attribute-choose").mCustomScrollbar({
                        theme: "minimal-dark"
                    });
                    $('.choose-attribute-choose').find('input').each(function () {
                        $(this).iCheck({
                            checkboxClass: 'icheckbox_flat-red',
                        });
                    });
                    L.dci.app.util._drag("query-choose-contain-id", "query-choose-header-contain-id");   //拖拽方法
                    $("#query-choose-contain-id")[0].offsetHeight;
                    $("#query-choose-contain-id").css("opacity", "1");

                    $('.query-choose-contain-close').on('click', { obj: _this }, _this.close);
                    $('.query-choose-contain button').on('click', { obj: _this }, _this.chooseresult);
                    $('.choose-style-choose').off('click', 'a', { obj: _this }, _this.tool);
                    $('.choose-style-choose').on('click', 'a', { obj: _this }, _this.tool);
                    $('.choose-style-choose-cs').off('click', 'a', { obj: _this }, _this._tool);
                    $('.choose-style-choose-cs').on('click', 'a', { obj: _this }, _this._tool);

                });
            }
        },
        /*关闭弹出窗体*/
        close: function (o) {
            var _this = o.data.obj;
            var obj = document.getElementById("query-choose-contain-id"); //解决浏览器兼容问题
            obj.parentNode.removeChild(obj);
            //$("#query-choose-contain-id").parent().parent().remove();
            if (_this.map)
                _this._map.activate(L.DCI.Map.StatusType.PAN, null, null, _this);

            for (var tool in _this.tools) {
                if (_this.tools[tool] != null) _this.tools[tool].disable();
            }
            _this._returndata(_this.data);
        },

        /*传输选择参数*/
        chooseresult: function (o) {
            var _this = o.data.obj;

            if (_this.attributeNode) {
                _this.data.query_attribute = [];
                $('.choose-attribute-choose').find('input').each(function () {
                    if ($(this).is(':checked')) {
                        _this.data.query_attribute.push($(this).parent().parent().children().eq(1).html());
                    }
                });
            }

            //if (_this.thirdchooseNode) {
            //    var name = $(".choose-test-choose select option:selected").text();
            //    _this.query.where("NAME='" + name + "'").run(function (error, featureCollection, response) {
            //        _this.data.query_content = featureCollection.features[0].geometry;
            //        return _this.data;
            //    });
            //}
            _this.close(o);
        },

        /*标绘方式*/
        tool: function (o) {
            L.DomEvent.stopPropagation(o);
            var _this = o.data.obj;
            var name = $(o.currentTarget).children().eq(1).html();
            _this._changeHandler(o.currentTarget.id, _this.currentHandler_id);
            //for (var i = 0; i < $(o.currentTarget).parent().children().length; i++) {
            //    if ($(o.currentTarget).parent().children().eq(i).hasClass('choose-style-choose-click'))
            //        $(o.currentTarget).parent().children().eq(i).removeClass('choose-style-choose-click');
            //}
            $(o.currentTarget).addClass('choose-style-choose-click');
            var mpgroup = L.DCI.App.pool.get("MultiMap");
            var map = mpgroup.getActiveMap();
            var mapGroup = L.DCI.App.pool.get("MultiMap").getMapGroup();
            for (var tool in _this.tools) {
                if (_this.tools[tool] != null) _this.tools[tool].disable();
            }
            switch (name) {
                case "点选择":
                    if (_this.tools.point == null)
                        _this.tools.point = new L.DCI.DrawPoints(map.map);
                    _this.tools.point.enable();
                    _this.data.query_style = '点选择';
                    break;
                case "线选择":
                    if (_this.tools.polyline == null)
                        _this.tools.polyline = new L.DCI.DrawPolylines(map.map);
                    _this.tools.polyline.enable();
                    _this.data.query_style = '线选择';
                    break;
                case "面选择":
                    if (_this.tools.polygon == null)
                        _this.tools.polygon = new L.DCI.DrawPolygons(map.map);
                    _this.tools.polygon.enable();
                    _this.data.query_style = '面选择';
                    break;
            }
        },

        /*文件选取方式*/
        _tool: function (o) {
            L.DomEvent.stopPropagation(o);
            var _this = o.data.obj;
            var name = $(o.currentTarget).children().eq(1).html();
            _this._changeHandler(o.currentTarget.id, _this.currentHandler_id);
            //for (var i = 0; i < $(o.currentTarget).parent().children().length; i++) {
            //    if ($(o.currentTarget).parent().children().eq(i).hasClass('choose-style-choose-click'))
            //        $(o.currentTarget).parent().children().eq(i).removeClass('choose-style-choose-click');
            //}
            $(o.currentTarget).addClass('choose-style-choose-click');
            var mpgroup = L.DCI.App.pool.get("MultiMap");
            var map = mpgroup.getActiveMap();
            var mapGroup = L.DCI.App.pool.get("MultiMap").getMapGroup();
            _this._map = map;
            switch (name) {
                case "CAD选择":
                    _this.queryType = "cad";
                    map.activate(L.DCI.Map.StatusType.SELECT, _this.findcscontain, _this.precall, _this);
                    break;
                case "SHP选择":
                    _this.queryType = "shp";
                    map.activate(L.DCI.Map.StatusType.SELECT, _this.findcscontain, _this.precall, _this);
                    break;
            }
            L.dci.app.util._drag("query-choose-contain-id", "query-choose-header-contain-id");
        },
        _hightLight: function (g) {
            var mpgroup = L.DCI.App.pool.get("MultiMap");
            var map = mpgroup.getActiveMap();
            var feature = {};//将esri类型的geometry转换为leaflet的类型
            feature.geometry = {};
            feature.geometry.coordinates = g.rings;
            feature.geometry.type = "Polygon";
            map.getHighLightLayer().clearLayers();
            L.dci.app.util.highLight(map, feature, true, false, "Polygon");
        },
        _changeHandler: function (id, currentId) {
            var mpgroup = L.DCI.App.pool.get("MultiMap");
            var map = mpgroup.getActiveMap();
            map.getHighLightLayer().clearLayers();
            if (currentId) {
                $("#" + currentId).removeClass("choose-style-choose-click");
            }
            $("#" + id).addClass("choose-style-choose-click");
            this.currentHandler_id = id;
            //移除鼠标状态
            this._map.activate(L.DCI.Map.StatusType.PAN, null, null, this);
            for (var tool in this.tools) {
                if (this.tools[tool] != null) this.tools[tool].disable();
            }
        },
        findcscontain: function (evt) {
            var _this = this;
            var layerGroups = null;
            if (_this.queryType == "shp") {
                layerGroups = this._map.shpLayerGroups;
            } else if (_this.queryType == "cad") {
                layerGroups = this._map.cadLayerGroups;
            }

            if ($("#choose-style-choose-cs-select").length == 0) {
                $(".choose-style-choose-cs").append("<select id='choose-style-choose-cs-select'></select>");
                $("#choose-style-choose-cs-select").bind('click', L.bind(function () {
                    var target = arguments[0].target;
                    this._changeHandler(target.id, this.currentHandler_id); //选择的范围类型变换
                    var selectFeature = this.queryResultFeatures[$(target).val()];
                    if (selectFeature) {
                        this.data.query_geo = L.dci.app.util.convertEsriToLeaflet(this._map, selectFeature, selectFeature.geometry.type);
                        L.dci.app.util.highLight(this._map, selectFeature, true, false, selectFeature.geometry.type);
                    }
                }, this));
            } else {
                $("#choose-style-choose-cs-select").empty();
                this.queryResultFeatures = [];
            }
            for (var i in layerGroups) {
                var layerG = layerGroups[i];
                L.dci.app.util.queryLayerGroup(layerG.group, evt, L.bind(function (features) {
                    var result_select = $(".choose-style-choose-cs select");
                    for (var k in features) {
                        if (!this.me.queryResultFeatures) this.me.queryResultFeatures = [];
                        this.me.queryResultFeatures.push(features[k]);
                        $(result_select).append('<option value="' + (this.me.queryResultFeatures.length - 1) + '">' + this.layerName + "_" + this.me.queryResultFeatures.length + '</option>');
                        $("#choose-style-choose-cs-select").click();
                    }
                }, { me: this, layerName: layerG.name }));
            }
        },
        precall: function () {
        },
    });


    L.DCI.DrawPoints = L.Draw.Marker.extend({
        lays: null,
        options: {
            clickable: false
        },
        addHooks: function () {
            this.options.icon = new L.Icon({
                iconUrl: L.DCI.App.symbol.pointSymbol.iconUrl,
                iconSize: L.DCI.App.symbol.pointSymbol.iconSize,
                iconAnchor: [L.DCI.App.symbol.pointSymbol.iconSize[0] / 2, L.DCI.App.symbol.pointSymbol.iconSize[1] + 10]
            });
            this.options.opacity = L.DCI.App.symbol.pointSymbol.opacity;
            L.Draw.Marker.prototype.addHooks.call(this);

            if (this._map) {
                this._map.on('click', this._onClick, this);
                this._map.on('mouseup', this._exist, this);
            }
        },

        removeHooks: function () {
            L.Draw.Marker.prototype.removeHooks.call(this);

            //!\ Still useful when control is disabled before any drawing (refactor needed?)
            this._map.off('click', this._onClick, this);
            this._map.off('mouseup', this._exist, this);
        },
        _exist: function (e) {
            if (e.originalEvent.button == 2) {
                this.disable();
            }
            else {
                this._poly = L.marker(e.latlng, this.options);
                this._poly.options.icon = new L.Icon({
                    iconUrl: L.DCI.App.symbol.pointSymbol.iconUrl,
                    iconSize: L.DCI.App.symbol.pointSymbol.iconSize,
                    iconAnchor: [L.DCI.App.symbol.pointSymbol.iconSize[0] / 2, L.DCI.App.symbol.pointSymbol.iconSize[1]]
                });
                //多屏同步显示
                if (this._poly) {
                    var mapGroup = L.DCI.App.pool.get("MultiMap").getMapGroup();
                    for (var q = 0; q < mapGroup.length; q++) {
                        var qmap = mapGroup[q].getMap();
                        if (this.lays == null) this.lays = [L.layerGroup([]), L.layerGroup([]), L.layerGroup([]), L.layerGroup([])];
                        var lay = L.marker(this._poly._latlng, this._poly.options);
                        this.lays[q].addLayer(lay);
                        //this.lays[q].addTo(qmap);
                        //mapGroup[q].clear();
                        mapGroup[q].getHighLightLayer().clearLayers();
                        mapGroup[q].getHighLightLayer().addLayer(lay);
                        if (L.DCI.App.pool.has("querycontain")) {
                            L.DCI.App.pool.get("querycontain").data.query_geo = lay;
                       }
                        if (L.DCI.App.pool.has("ZuoBiaoQuery")) {
                            L.DCI.App.pool.get("ZuoBiaoQuery").drawpointCallback({ layer: lay });
                        }
                    }
                }
            }
        },
        clear: function () {
            if (this.lays == null) return;
            //多屏同步显示
            for (var q = 0; q < this.lays.length; q++) {
                this.lays[q].clearLayers();
            }
        },

        _onClick: function (e) {

        }
    });

    /*绘制线*/
    L.DCI.DrawPolylines = L.Draw.Polyline.extend({

        lays: null,
        options: {
            repeatMode: true,
            showLength: false, // Whether to display distance in the tooltip
            clickable: false
        },
        addHooks: function () {
            this.options.shapeOptions = {
                color: L.DCI.App.symbol.polylineSymbol.color,
                weight: L.DCI.App.symbol.polylineSymbol.weight,
                opacity: L.DCI.App.symbol.polylineSymbol.opacity,
                clickable: false
            };
            L.Draw.Polyline.prototype.addHooks.call(this);
            if (this._map) {
                this._markerGroup = new L.LayerGroup();
                this._map.addLayer(this._markerGroup);

                this._markers = [];
                this._map.on('click', this._onClick, this);
                this._mouseMarker.on('contextmenu', function () { this.disable(); }, this);
                this._startShape();
            }
        },

        removeHooks: function () {
            L.Draw.Polyline.prototype.removeHooks.call(this);

            this._clearHideErrorTimeout();

            //!\ Still useful when control is disabled before any drawing (refactor needed?)
            this._map.off('mousemove', this._onMouseMove);
            this._clearGuides();
            this._container.style.cursor = '';

            this._removeShape();

            this._map.off('click', this._onClick, this);
        },

        _startShape: function () {
            this._drawing = true;
            this._poly = new L.Polyline([], this.options.shapeOptions);

            this._container.style.cursor = 'crosshair';

            this._updateTooltip();
            this._map.on('mousemove', this._onMouseMove, this);
        },

        _finishShape: function () {
            this._drawing = false;

            this._cleanUpShape();
            this._clearGuides();

            this._updateTooltip(this.fylatlng);

            this._map.off('mousemove', this._onMouseMove, this);
            this._container.style.cursor = '';

            //多屏同步显示
            if (this._poly) {
                var mapGroup = L.DCI.App.pool.get("MultiMap").getMapGroup();
                for (var q = 0; q < mapGroup.length; q++) {
                    var qmap = mapGroup[q].getMap();
                    if (this.lays == null) this.lays = [L.layerGroup([]), L.layerGroup([]), L.layerGroup([]), L.layerGroup([])];
                    var lay = L.polyline(this._poly._latlngs, this._poly.options);
                    this.lays[q].addLayer(lay);
                    //this.lays[q].addTo(qmap);
                    //mapGroup[q].clear();
                    mapGroup[q].getHighLightLayer().clearLayers();
                    mapGroup[q].getHighLightLayer().addLayer(lay);
                    if (L.DCI.App.pool.has("querycontain")) {
                        L.DCI.App.pool.get("querycontain").data.query_geo = lay;
                    }
                }
            }
            L.Draw.Polyline.prototype._finishShape.call(this);
        },
        clear: function () {
            if (this.lays == null) return;
            //多屏同步显示
            for (var q = 0; q < this.lays.length; q++) {
                this.lays[q].clearLayers();
            }
        },
        _onZoomEnd: function () {
            L.Draw.Polyline.prototype._onZoomEnd.call(this);
            this._updateTooltip(this.fylatlng);
        },
        _onMouseMove: function (e) {
            L.Draw.Polyline.prototype._onMouseMove.call(this, e);
            this.fylatlng = e.latlng;
        },
        _removeShape: function () {
            if (!this._poly)
                return;
            this._map.removeLayer(this._poly);
            delete this._poly;
            this._markers.splice(0);
            this._markerGroup.clearLayers();
        },

        _onClick: function (e) {
            if (!this._drawing) {
                this._removeShape();
                this._startShape();
                return;
            }
        },

        _getTooltipText: function () {
            var labelText = L.Draw.Polyline.prototype._getTooltipText.call(this);
            if (!this._drawing) {
                labelText.text = '点击完成绘制';
            }
            return labelText;
        },
        _onMouseDown: function (e) {
            if (e.originalEvent.button == 2) return;
            L.Draw.Polyline.prototype._onMouseDown.call(this, e);
        },

        _onMouseUp: function (e) {
            if (e.originalEvent.button == 2) return;
            L.Draw.Polyline.prototype._onMouseUp.call(this, e);
        }
    });

    /*绘制面类*/
    L.DCI.DrawPolygons = L.Draw.Polygon.extend({

        lays: null,
        options: {
            repeatMode: true,
            showArea: false,
            clickable: false
        },
        addHooks: function () {
            this.options.shapeOptions = {
                color: L.DCI.App.symbol.polygonSymbol.color,
                weight: L.DCI.App.symbol.polygonSymbol.weight,
                opacity: L.DCI.App.symbol.polygonSymbol.opacity,
                fill: L.DCI.App.symbol.polygonSymbol.fill,
                fillColor: L.DCI.App.symbol.polygonSymbol.fillColor, //same as color by default
                fillOpacity: L.DCI.App.symbol.polygonSymbol.fillOpacity,
                clickable: false
            };
            L.Draw.Polygon.prototype.addHooks.call(this);
            if (this._map) {
                this._markerGroup = new L.LayerGroup();
                this._map.addLayer(this._markerGroup);

                this._markers = [];
                this._map.on('click', this._onClick, this);
                this._mouseMarker.on('contextmenu', function () { this.disable(); }, this);
                this._startShape();
            }
        },

        removeHooks: function () {
            L.Draw.Polygon.prototype.removeHooks.call(this);

            this._clearHideErrorTimeout();

            //!\ Still useful when control is disabled before any drawing (refactor needed?)
            this._map.off('mousemove', this._onMouseMove);
            this._clearGuides();
            this._container.style.cursor = '';

            this._removeShape();

            this._map.off('click', this._onClick, this);
        },

        _startShape: function () {
            this._drawing = true;
            this._poly = new L.Polygon([], this.options.shapeOptions);

            this._container.style.cursor = 'crosshair';

            this._updateTooltip();
            this._map.on('mousemove', this._onMouseMove, this);
        },

        _finishShape: function () {
            this._drawing = false;

            this._cleanUpShape();
            this._clearGuides();

            this._updateTooltip(this.fylatlng);

            this._map.off('mousemove', this._onMouseMove, this);
            this._container.style.cursor = '';

            //多屏同步显示
            if (this._poly) {
                var mapGroup = L.DCI.App.pool.get("MultiMap").getMapGroup();
                for (var q = 0; q < mapGroup.length; q++) {
                    var qmap = mapGroup[q].getMap();
                    if (this.lays == null) this.lays = [L.layerGroup([]), L.layerGroup([]), L.layerGroup([]), L.layerGroup([])];
                    var lay = L.polygon(this._poly._latlngs, this._poly.options);
                    this.lays[q].addLayer(lay);
                    //this.lays[q].addTo(qmap);
                    //mapGroup[q].clear();
                    mapGroup[q].getHighLightLayer().clearLayers();
                    mapGroup[q].getHighLightLayer().addLayer(lay);

                    if (L.dci.app.pool.has("querycontain") == true) {
                        L.DCI.App.pool.get("querycontain").data.query_geo = lay;
                    }
                    //用地平衡分析调用
                    if (L.dci.app.pool.has("LandBalance") == true) {
                        L.dci.app.pool.get("LandBalance").getDrawPolygonsRegion(lay);
                    }
                    //用地开发强度评价调用
                    if (L.dci.app.pool.has("LandStrength") == true) {
                        L.dci.app.pool.get("LandStrength").getDrawPolygonsRegion(lay);
                    }
                    //用地平衡-顺德
                    if (L.dci.app.pool.has("analysisydph") == true) {
                        L.dci.app.pool.get("analysisydph").getDrawPolygonsRegion(lay);
                    }
                }
            }
            L.Draw.Polyline.prototype._finishShape.call(this);
        },
        clear: function () {
            if (this.lays == null) return;
            //多屏同步显示
            for (var q = 0; q < this.lays.length; q++) {
                this.lays[q].clearLayers();
            }
        },
        _onZoomEnd: function () {
            L.Draw.Polyline.prototype._onZoomEnd.call(this);
            this._updateTooltip(this.fylatlng);
        },

        _onMouseMove: function (e) {
            L.Draw.Polyline.prototype._onMouseMove.call(this, e);
            this.fylatlng = e.latlng;
        },

        _removeShape: function () {
            if (!this._poly)
                return;
            this._map.removeLayer(this._poly);
            delete this._poly;
            this._markers.splice(0);
            this._markerGroup.clearLayers();


        },

        _onClick: function (e) {
            if (!this._drawing) {
                this._removeShape();
                this._startShape();
                return;
            }
        },

        _getTooltipText: function () {
            var labelText = L.Draw.Polygon.prototype._getTooltipText.call(this);
            if (!this._drawing) {
                labelText.text = '点击完成绘制';
            }
            return labelText;
        },

        _getMeasurementString: function () {
            return;
            var area = this._area;

            if (!area) {
                return null;
            }

            return L.GeometryUtil.readableArea(area, true);
        },

        _vertexChanged: function (latlng, added) {
            var latLngs = this._poly.getLatLngs();
            this._area = L.GeometryUtil.geodesicArea(latLngs);
            L.Draw.Polyline.prototype._vertexChanged.call(this, latlng, added);
        },
        _onMouseDown: function (e) {
            if (e.originalEvent.button == 2) return;
            L.Draw.Polyline.prototype._onMouseDown.call(this, e);
        },

        _onMouseUp: function (e) {
            if (e.originalEvent.button == 2) return;
            L.Draw.Polyline.prototype._onMouseUp.call(this, e);
        }
    });
    return L.DCI.Contain;
});

